<?php

namespace App\Http\Service;

use App\Jobs\CheckHouse;
use App\Model\Business;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\CountryLog;
use App\Model\Device;
use App\Model\DeviceWarning;
use App\Model\House;
use App\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CountryService
{
    /**获取token
     * @return mixed|string
     * @throws \Exception
     */
    public function getToken(){
        $key = 'redis_country_token';
//        if(Redis::exists($key)){
//            $token = Redis::get($key);
//            return $token;
//        }
        $uri ='https://countryside.hesc.com.cn/gw/getAccessToken';
        $data['appid'] = '43f7b900f37a11eb415cb69b8bedb83a';
        $data['appsecret'] = 'aa9066b000ba11ec63656952524d35ea';
        $result = $this->httpGetRequest($uri,$data);
        Log::info($result);
        $result = json_decode($result,true);
        if($result && $result['code'] == 0){
            Redis::setex($key,60*60*2,$result['obj']['accessToken']);
        }else{
           return '';
        }
        return $result['obj']['accessToken'];
    }

    /**推送房东数据
     * @param $house
     * @return string|void
     * @throws \Exception
     */
    public function pushBusiness($data){
        $uri = 'https://countryside.hesc.com.cn/gw/application/rent/rentLandlord/security/add';
        $token = $this->getToken();
        if(!$token){
            return '';
        }
        $result = $this->httpPostRequest($uri,$data,$token);
        $this->createLog($data,$result,2);
    }


    public function pushDevice($data){
        $uri = 'https://countryside.hesc.com.cn/gw/application/rent/rentElectricitymeterInfo/security/add';
        $token = $this->getToken();
        if(!$token){
            return '';
        }
        $result = $this->httpPostRequest($uri,$data,$token);
        $this->createLog($data,$result,3);
    }

    public function pushWarning($data){
        $uri = 'https://countryside.hesc.com.cn/gw/application/rent/rentElectricitymeterAlarm/security/add';
        $token = $this->getToken();
        if(!$token){
            return '';
        }
        $result = $this->httpPostRequest($uri,$data,$token);
        Log::info($result);
//        $response = json_decode($result,true);
//        $warningData = DeviceWarning::query()->where('id',$data['id'])->first();
//        if($response['code'] == 0){
//            $warningData->is_push = 1;
//        }else{
//            $warningData->is_push = 2;
//        }
//        $warningData->save();
    }

    /**推送租客数据
     * @param $data
     * @return string|void
     * @throws \Exception
     */
    public function pushTenant($data){
        $token = $this->getToken();
        if(!$token){
            return '';
        }
        $uri = 'https://countryside.hesc.com.cn/gw/application/rent/rentTenant/security/add';
        $result = $this->httpPostRequest($uri,$data,$token);
        $this->createLog($data,$result);
    }

    public function autoPush1($limit){
        $warning = DeviceWarning::query()->where('is_push',0)
            ->limit($limit)->get();
        $countryService = new CountryService();
        foreach($warning as $v){
            $house = House::query()->where('id',$v->house_id)->first();
            if($house && $house->country_code){
                $device = Device::query()->where('id',$v->device_id)->first();
                $push['regionCode'] = $house->regionCode;
                $push['sn'] = $device->sn;
                $push['warningDate'] = date('Y-m-d');
                $push['startDate'] = $v->start;
                $push['endDate'] = $v->end;
                $push['consume'] =  $v->xh>0?($v->xh/1000):0;
                $push['phone'] = $v->tenant_mobile;
                $user = User::query()->where('mobile',$v->tenant_mobile)->first();
                if($user){
                    $push['name'] = $user->nickname?$user->nickname:'未实名';
                    $push['address'] = $v->address;
                    $push['id'] = $v->id;
                    $countryService = new CountryService();
                    $countryService->pushWarning($push);
                }else{
                    $v->is_push = 3;
                    $v->save();
                }
            }else{
                $v->is_push = 3;
                $v->save();
            }
        }

    }

    public function autoPush(){
//        House::query()->where('estate_name','like','%横店%')->update(['country_code'=>'330783123888','is_push'=>0]);
        $houses = House::query()
            ->where('estate_name','like','%横店%')
            ->where('is_push',0)
            ->select('business_id')
            ->distinct()
            ->get()
            ->pluck('business_id')
            ->toArray();
        foreach ($houses as $k => $house) {
            if (!$house) {
                unset($houses[$k]);
            }
            dispatch(new CheckHouse($house))->delay(3);
        }

    }

    public function createLog($request,$response,$type = 1){
        $save['type'] = $type;
        $save['regionCode'] = $request['regionCode'];
        if($type == 3){
            $save['lat'] = $request['latitude'];
            $save['lng'] =$request['longitude'];
            $save['sn'] = $request['sn'];
            $save['house_id'] = $request['house_id'];
            $response = json_decode($response,true);
            if($response['code'] == 0){
                $save['status'] = 1;
                House::query()->where('id',$request['house_id'])
                    ->update(['is_push'=>2]);
            }else{
                $save['status'] = 2;
            }
        }else{
            $save['address'] = $request['address'];
            $save['phone'] = $request['phone'];
            $save['name'] = $request['name'];
            $response = json_decode($response,true);
            if($response['code'] == 0){
                $save['status'] = 1;
                if($type == 2){
                    House::query()->where('id',$request['house_id'])
                        ->update(['is_push'=>1]);
                    $save['house_id'] = $request['house_id'];
                }else{
                    if(isset($request['tenant_id'])){
                        ContractTenant::query()->where('id',$request['tenant_id'])
                            ->update(['is_push'=>1]);
                        $save['tenant_id'] = $request['tenant_id'];
                    }
                }
            }else{
                $save['status'] = 2;
            }
        }
        $save['result'] =json_encode($response,true);
        $save['request'] = json_encode($request,true);
        CountryLog::create($save);
    }

    public function httpPostRequest($url = '', $parameters = [], $token = '',$common_parameters = [])
    {
        $parameters = json_encode($parameters);
        $request_url = $url . '?' . http_build_query($common_parameters);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
        $headers = [
            "Content-Type: application/json"
        ];

        // Add token to headers if provided
        if (!empty($token)) {
            $headers[] = "accessToken:" . $token;
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);
            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);
        return $response;
    }

    public function httpGetRequest($url, $data = [])
    {
        foreach ($data as $key => $value) {
            if (!is_string($value)) {
                $data[$key] = json_encode($value);
            }
        }

        $request_url = $url . '?' . http_build_query($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // 验证 SSL 证书是否由受信任的 CA 签发
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);
            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);
        return $response;
    }


}
